<?php
/**
 * Created by Zend Studio.
 * User: FDG348
 * Date: 2017/10/9
 * Time: 08:46
 */
namespace backend\models;

use Yii;
use yii\db\ActiveRecord;

class GoodsSourceEdit extends ActiveRecord{
    const STATUS_ENABLE = 1;
    const STATUS_DISABLE = 0;

    public static function tableName(){
        return '{{%goods_source_edit}}';
    }

    public function rules(){
        return [
            ['use_flg','default','value'=>self::STATUS_DISABLE],
            ['creator','getCreator'],
            ['create_time','date']
        ];
    }

    /**
     * @获取创建人
     */
    public function getCreator(){
        $userInfo = \common\helps\tools::getloginUserInfo();
        if($userInfo){
            $userName = $userInfo->userName;
        }else{
            $userName = '';
        }
        return $userName;
    }

    /**
     * @param $data_url array 素材链接
     * @param $data_sort array 素材排序
     * @param $data_type array 素菜类型
     * @param $goods array 商品详情
     */
    public function addSource($data_url,$data_sort,$data_type,$goods){
        $list = array();
        foreach($data_url as $key=>$value){
            if (!$value) continue;
            $list[] = [$goods['main_goods_id'],$goods['goods_id'],$goods['sku'],
                $data_type[$key],$value,$value,$data_sort[$key],$this->getCreator(),date('Y-m-d H:i:s',time())];
        }
        $field_name = ['main_goods_id','goods_id','sku','source_type','source_url','source_link','sort','creator','create_time'];
        $ret = Yii::$app->db->createCommand()->batchInsert('j_goods_source_edit', $field_name, $list)->execute();
        return $ret;
    }
    
    public function getSourceList($goods_id){
        $result = array();
        $bath_url = Yii::$app->params['imageBathUrl'] . '/';
        $where = ['s.goods_id'=>$goods_id];
        $list = $this::find()->alias('s')->leftJoin('j_goods_sale_edit as g','s.goods_id = g.goods_id')
        ->where($where)->orderBy('s.sort asc')->select('s.id,s.source_type,s.source_url,s.source_link,g.goods_name_cn')->asArray()->all();
        if(!empty($list)){
            foreach($list as &$value){
                if($value['source_type'] == 1){
                    $value['source_url'] = $bath_url . 'uploads/2017-09-26/150639543251916.png';
                }else{
                    $value['source_url'] = $bath_url . $value['source_url'];
                }
                $value['source_link'] = $bath_url . $value['source_link'];
            }
            $result = $list;
        }
        return $result;
    }
}